<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>添加品牌</title>
    </head>
    <body>
        <h3>添加品牌</h3>
        <!--表单直接提交属于同步请求方式提交表单，为了使用异步方式以及AJAX+JSON异步方式提交所以要将action属性值设为空并将提交按钮的type属性值设为button-->
        <!--action的属性值为浏览器提交到服务器的资源路径-->
        <!--将action属性值由具体的url改为空-->
        <form action="" method="post">
            品牌名称：<input id="brandName" name="brandName"><br>
            企业名称：<input id="companyName" name="companyName"><br>
            排序：<input id="ordered" name="ordered"><br>
            描述信息：<textarea rows="5" cols="20" id="description" name="description"></textarea><br>
            状态：
            <input type="radio" name="status" value="0">禁用
            <input type="radio" name="status" value="1">启用<br>
            <!--将提交按钮的type属性由submit改为button-->
            <input type="button" id="btn"  value="提交">
        </form>

        <script src="js/axios-0.18.0.js"></script>

        <script>
            //1 给提交按钮绑定单击事件
            document.getElementById("btn").onclick = function () {
                //2 将表单数据转为JSON字符串数据
                //2.1 设置JS对象
                var formData = {
                    brandName:"",
                    companyName:"",
                    ordered:"",
                    description:"",
                    status:"",
                };
                //2.2 获取表单数据
                let brandName = document.getElementById("brandName").value;
                let companyName = document.getElementById("companyName").value;
                let ordered = document.getElementById("ordered").value;
                let description = document.getElementById("description").value;
                // 获取单选框数组
                let status = document.getElementsByName("status");
                //2.3 给JS对象设置数据
                formData.brandName = brandName;
                formData.companyName = companyName;
                formData.ordered = ordered;
                formData.description = description;
                // 判断选择的是禁用还是启用并设置数据
                for (let i = 0; i < status.length; i++) {
                    if(status[i].checked){
                        formData.status = status[i].value ;
                    }
                }
                //console.log(formData);
                //2 发送Ajax请求
                axios({
                    method:"post",
                    url:"http://localhost:8080/AxiosJsonDemoo/addServlet",
                    //3 JSON数据格式发送请求
                    // formData为JS对象，Axios会自动将JS对象转为JSON字符串然后在传给服务端
                    data:formData
                }).then(function (resp) {
                    //4 获取响应数据并判断响应数据是否为success
                    if(resp.data == "success"){
                        location.href = "http://localhost:8080/AxiosJsonDemoo/brand.html";
                    }
                })
            }
        </script>
    </body>
</html>
